<?php

class View
{

	/**
	 * @var array
	 */
	static protected $_paths = array(TEMPLATE_PATH,SYSTEM_TEMPLATE_PATH);

	/**
	 * @var View
	 */
	static protected $_inst = null;

	/**
	 * lock this method
	 * constructor
	 */
	private function __construct()
	{
		self::$_inst = $this;
	}

	/**
	 * a quiclier way single call to global helper
	 * @return array
	 */
	public function __call($name, $args)
	{
		return call_user_func_array(array(
				Agis::help($name),
				$name
		), $args);
	}

	/**
	 * better way to get helpers
	 */
	public function __get($name)
	{
		return Agis::getHelper($name);
	}

	/**
	 * @param string $path
	 * @return void
	 */
	static public function add_include_path($path)
	{
		array_unshift(self::$_paths, $path);
	}

	static public function set_dir($name)
	{
		self::$_dir = $name;
	}

	/**
	 * @return View
	 */
	static public function inst()
	{
		return (null == self::$_inst) ? self::$_inst : new self;
	}

	/**
	 * find a path
	 * @param string $script
	 * @param bool $include
	 * @param array $paths
	 * @return string
	 */
	static public function __find_script($script, $use_include_path)
	{

		if (false == $use_include_path)
		{
			if (file_exists($script))
			{
				return $script;
			}
			return null;
		}

		foreach (self::$_paths as $path)
		{
			if (file_exists($path . '/' . $script))
			{
				return $path . '/' .  $script;
			}
		}

		return null;
	}

	/**
	 * escape string
	 * @param string $string
	 * @return string
	 */
	static public function escape($string)
	{
		return htmlspecialchars($string, ENT_COMPAT, 'UTF8');
	}

	/**
	 * process render
	 * @param array
	 */
	static public function render($data, $script, $use_include_path = 1)
	{
		$data = (array)$data;

		ob_start();

		$__script = self::__find_script($script, $use_include_path);

		if (null == $__script)
		{
			throw new Exception("$script not found in view paths.");
		}

		extract($data, EXTR_SKIP);

		include $__script;

		return ob_get_clean();
	}

}
